import axios from '@/axios'
import createTreeDataSource from '@/utils/DataSource'

let {
    tree,
    flatTree,
    dataSource,
    loadTree,
	currentVersion
} = createTreeDataSource(loader);

async function loader(force : boolean = false) {
    let msg = await axios.post("/api/dict/GetDictionaries", { force });
    let data = [];
    for (let ele of (msg.data || [])) {
        data.push({
            key: ele.ID,
            title: ele.Name,
            ...ele
        });
    }
    return data;
}

// interface TreeNode {
//     key: string,
//     title: string,
//     Entries?: Array<DictionaryEntry>
//     [prop: string]: any
// }

interface DictionaryEntry {
    "DataKey": string,
    "DataValue": string,
    "CanEdit": boolean,
    "CanDelete": boolean,
    "Visible": boolean,
    "Enable": boolean,
    "DisplayOrder": number,
}

// -- 处理字典 -- //
export default function toText(dict: string, key: string): string {
    let ele = flatTree.find(e => e.title === dict);
    if (ele && ele.Entries && ele.Entries.length) {
        let entry = ele.Entries.find((x: any) => key.toString && x.DataKey === key.toString());
        return entry ? entry.DataValue : "数据项不存在";
    }
    return "字典不存在";
}

async function ensureDictionary(dict: string, filter?: string): Promise<{ name: string, canEdit: boolean, canDelete: boolean, entries: Array<DictionaryEntry> }> {
    await loadTree();
    return getDictionary(dict, filter);
}

function getDictionary(dict: string, filter?: string): { name: string, type: string, canEdit: boolean, canDelete: boolean, entries: Array<DictionaryEntry> } {
    interface internal { Name: string, From: number, CanEdit: boolean, CanDelete: boolean, Entries: Array<DictionaryEntry> };
    if (!flatTree.length) return { name: "", type: "string", canDelete: false, canEdit: false, entries: [] }
    let ele: internal = flatTree.find(e => e.title === dict || e.key === dict) as unknown as internal;
    let entries = ele && ele.Entries ? ele.Entries.filter(e => !filter || e.DataKey.indexOf(filter) >= 0 || e.DataValue.indexOf(filter) >= 0) : [];
    return {
        name: ele.Name,
        type: ele.From === 0 ? "number" : "string",
        canEdit: ele.CanEdit,
        canDelete: ele.CanDelete,
        entries
    }
}

export {
    loadTree as loadDictionary,
    getDictionary,
    dataSource,
    ensureDictionary,
	currentVersion as dictVersion
}